import { create } from "zustand";
import {
  createJSONStorage, // 持久化存储
  devtools, // 调试
  persist, // 持久化
  subscribeWithSelector, // 为 store 的订阅功能增加了基于选择器的能力，允许你只订阅状态中特定的部分变化
} from "zustand/middleware";
import { immer } from "zustand/middleware/immer";

interface Person {
  name: string;
  age: number;
  hobby: {
    sing: string;
    dance: string;
    rap: string;
    basketball: string;
  };
  setAge: (age?: number) => void;
  setName: (name?: string) => void;
  setHobbyRap: (rap: string) => void;
  setHobbyDance: (dance: string) => void;
  setHobbyBasketball: (basketball: string) => void;
}

// 自定义编写中间件
// const logger = (config: any) => (set: any, get: any, api: any) =>
//   config(
//     (...args: any[]) => {
//       console.log("before", get());
//       set(...args);
//       console.log("after", get());
//     },
//     get,
//     api
//   );

// 常用的中间件：devtools(开发调试)、persist(持久化)

const userPersonStore = create<Person>()(
  immer(
    devtools(
      persist(
        subscribeWithSelector((set) => ({
          name: "user",
          age: 18,
          hobby: {
            sing: "sing",
            dance: "dance",
            rap: "rap",
            basketball: "basketball",
          },
          setAge: () => {
            set((state) => {
              state.age += 1;
            });
          },
          setName: () => { 
            set((state) => {
              state.name = "zhangsan" + Math.random().toFixed(2);
            });
          },
          setHobbyRap: (rap) =>
            set((state) => {
              state.hobby.rap = rap;
            }),
          setHobbyDance: (dance) =>
            set((state) => {
              state.hobby.dance = dance;
            }),
          setHobbyBasketball: (basketball) =>
            set((state) => {
              state.hobby.basketball = basketball;
            }),
        })),
        {
          name: "personStore", // 仓库名称(唯一)
          storage: createJSONStorage(() => localStorage), // 存储方式 可选 localStorage sessionStorage IndexedDB 默认localStorage
          //   partialize: (state) => ({
          //     name: state.name,
          //     hobby: state.hobby
          // }) // 部分状态持久化
        }
      ),
      {
        name: "personStore",
        enabled: process.env.NODE_ENV === "development",
      }
    )
  )
);

export default userPersonStore;
